#include "../source/common/net.hpp"
#include "../source/common/dispatcher.hpp"
#include "../source/client/rpc_caller.hpp"
#include "../source/common/log.hpp"

#include <memory>
#include <functional>
#include <thread>

void callBack(const Json::Value &result)
{
    LOG(JsonMuduoRPC::DEBUG, "result: %d", result.asInt());
}

int main()
{
    JsonMuduoRPC::client::Requestor::ptr requestor = std::make_shared<JsonMuduoRPC::client::Requestor>();
    JsonMuduoRPC::client::RPCCaller::ptr rpc_caller = std::make_shared<JsonMuduoRPC::client::RPCCaller>(requestor);

    auto on_response = std::bind(&JsonMuduoRPC::client::Requestor::onResponse, requestor.get(),
                                 std::placeholders::_1, std::placeholders::_2);

    auto dispatcher = std::make_shared<JsonMuduoRPC::Dispatcher>();
    dispatcher->registerHandler<JsonMuduoRPC::RPCResponse>(JsonMuduoRPC::MType::RSP_RPC, on_response); // 注册映射

    JsonMuduoRPC::BaseClient::ptr client = JsonMuduoRPC::ClientFactory::create("127.0.0.1", 8080);
    client->setMessageCallBack(std::bind(&JsonMuduoRPC::Dispatcher::onMessage, dispatcher.get(),
                                         std::placeholders::_1, std::placeholders::_2));
    client->connect();

    JsonMuduoRPC::BaseConnection::ptr con = client->connection();
    Json::Value params;
    params["num1"] = 11;
    params["num2"] = 22;
    Json::Value result;
    bool ret = rpc_caller->call(con, "ADD", params, result);
    if (ret == false)
        LOG(JsonMuduoRPC::ERROR, "请求处理失败");
    else
        LOG(JsonMuduoRPC::DEBUG, "result: %d", result.asInt());

    params["num1"] = 33;
    params["num2"] = 44;
    JsonMuduoRPC::client::RPCCaller::JsonAsyncResponse async_result;
    ret = rpc_caller->call(con, "ADD", params, async_result);
    if (ret == false)
        LOG(JsonMuduoRPC::ERROR, "请求处理失败");
    else
        LOG(JsonMuduoRPC::DEBUG, "result: %d", async_result.get().asInt());

    params["num1"] = 55;
    params["num2"] = 66;
    ret = rpc_caller->call(con, "ADD", params, callBack);
    if (ret == false)
        LOG(JsonMuduoRPC::ERROR, "请求处理失败");

    std::this_thread::sleep_for(std::chrono::seconds(10));

    client->shutdown();

    return 0;
}